#!/bin/sh

TIP="Preparing to initialize configs related to NVIDIA graphics..."

# 翻译文本 | Translation variables
case "${LANGUAGE:-$LANG}" in
es*)
	TIP="Preparándose para inicializar la configuración relacionada con los gráficos NVIDIA..."
	;;
zh*)
	TIP="即将初始化 NVIDIA 显卡相关配置文件......"
	;;
esac

# 提示文字 | Tip
echo "$TIP"

# 获取显卡 BusID | Get device BusID
# 仅获取第一张 NVIDIA 显卡的 PCI 设备地址 | Only get the first device BusID
NVIDIA_BusID=$(lspci | egrep 'VGA|3D' | grep 'NVIDIA' | cut -d ' ' -f 1 | sed -r 's/0?(.)/\1/' | sed -e 's/:0/:/g' -e 's/\./:/g' | head -n 1)

Intel_BusID=$(lspci | egrep 'VGA|3D' | grep 'Intel' | cut -d ' ' -f 1 | sed -r 's/0?(.)/\1/' | sed -e 's/:0/:/g' -e 's/\./:/g')

# 生成 xorg.conf | Generate xorg.conf
echo '# dde-dock-graphics-plugin: X configuration file generated by dde-dock-plugins
# dde-dock-graphics-plugin: version 2.0

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    Option         "AllowNVIDIAGPUScreens"
EndSection

Section "Module"
	Load "modesetting"
EndSection

Section "Device"
    Identifier     "GFX0"
    Driver         "modesetting"
    VendorName     "Intel Corporation"
    BusID          "PCI:'$Intel_BusID'"
EndSection

Section "Device"
    Identifier     "PEGP"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BusID          "PCI:'$NVIDIA_BusID'"
EndSection

Section "Screen"
    Identifier     "IGPU"
    Device         "GFX0"
EndSection

Section "Screen"
    Identifier     "DGPU"
    Device         "PEGP"
    Option         "AllowEmptyInitialConfiguration"
    Option         "Coolbits" "28"
EndSection' | sudo tee /etc/X11/xorg.conf.bak >/dev/null

# 生成 nvidia-graphics-drivers.conf | Generate nvidia-graphics-drivers.conf
echo 'options nvidia-drm modeset=1' | sudo tee /etc/modprobe.d/nvidia-graphics-driver.conf.bak >/dev/null

# 生成 display_setup.sh | Generate display_setup.sh
echo '#!/bin/sh
xrandr --setprovideroutputsource modesetting NVIDIA-0
xrandr --auto
xrandr --dpi 96' | sudo tee /etc/lightdm/display_setup.sh >/dev/null
sudo chmod +x /etc/lightdm/display_setup.sh
